package cn.flink.exercise;

import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.*;
import org.apache.flink.util.OutputTag;

import java.text.ParseException;
import java.time.Duration;
import java.util.List;
import java.util.Map;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * 下单未支付统计
 * 
 * @author mayong
 * @date 2023/05/07
 **/
public class unPayFlinkStat {

    private   static FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> socketTextStream = env.socketTextStream("bigdata01", 9999);

        KeyedStream<UserBehavior, Tuple> keyedStream = socketTextStream.map(new MapFunction<String, UserBehavior>() {
            public UserBehavior map(String value) throws Exception {
                String[] strings = value.split(",");
                return new UserBehavior(strings[0], strings[1], strings[2], strings[3], strings[4]);
            }
            //添加watermark
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                //指定对应的TimestampAssigner
                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                    @Override
                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                        //指定EventTime对应的字段
                        long extractTimestamp = 0;
                        try {
                            extractTimestamp = fastDateFormat.parse(element.timestamp).getTime();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        return extractTimestamp;
                    }
                })).keyBy("userId", "itemId");

        Pattern<UserBehavior, UserBehavior> pattern = Pattern.<UserBehavior>begin("start").where(new SimpleCondition<UserBehavior>() {
            @Override
            public boolean filter(UserBehavior orderDetail) throws Exception {

                if (orderDetail.behavior.equals("buy")) {
                    return true;
                }
                return false;
            }
        }).followedBy("second").where(new SimpleCondition<UserBehavior>() {
            @Override
            public boolean filter(UserBehavior orderDetail) throws Exception {

                if (!orderDetail.behavior.equals("buy")) {
                    return true;
                }
                return false;
            }
            //指定有效的时间约束
        }).within(Time.seconds(10));

        PatternStream<UserBehavior> patternStream = CEP.pattern(keyedStream, pattern).inEventTime();

        OutputTag outputTag = new OutputTag("timeout", TypeInformation.of(UserBehavior.class));

        SingleOutputStreamOperator<UserBehavior> result = patternStream.select(outputTag, new MyPatternTimeoutFunction(), new MyPatternSelectFunction());

        result.getSideOutput(outputTag).print("超时的订单：");

        env.execute("CheckOrderTimeoutWithCepByJava");

    }

    static class MyPatternSelectFunction implements PatternSelectFunction<UserBehavior,UserBehavior> {

        @Override
        public UserBehavior select(Map<String, List<UserBehavior>> patternMap) throws Exception {

            List<UserBehavior> secondOrderDetails = patternMap.get("second");
            //支付成功的订单
            UserBehavior orderDetailSuccess = secondOrderDetails.iterator().next();
            //返回
            return orderDetailSuccess;
        }
    }

    //todo: 提取超时的订单数据
    static class MyPatternTimeoutFunction implements PatternTimeoutFunction<UserBehavior,UserBehavior> {
        @Override
        public UserBehavior timeout(Map<String, List<UserBehavior>> patternMap, long timeoutTimestamp) throws Exception {

            List<UserBehavior> startTimeoutOrderDetails = patternMap.get("start");
            //超时订单
            UserBehavior orderDetailTimeout = startTimeoutOrderDetails.iterator().next();
            //返回
            return orderDetailTimeout;

        }
    }

    public static class UserBehavior{
        public String userId;
        public String itemId;
        public String categoryId;
        public String behavior;
        public String timestamp;
        //无参构造必须带上
        public UserBehavior() {
        }
        public UserBehavior(String userId, String itemId, String categoryId, String behavior, String timestamp) {
            this.userId = userId;
            this.itemId = itemId;
            this.categoryId = categoryId;
            this.behavior = behavior;
            this.timestamp = timestamp;
        }
        @Override
        public String toString() {
            return userId+"\t"+itemId+"\t"+categoryId+"\t"+behavior+"\t"+timestamp;
        }
    }

}
